//
//  MainVM.m
//  KeTianDemo
//
//  Created by jay on 2020/8/24.
//  Copyright © 2020 jay. All rights reserved.
//

#import "MainVM.h"
#import "TXHttpService.h"

@implementation MainVM

-(id)init {
    self = [super init];
    if (self) {
        self.pagenum = 0;
        self.pagesize = 50;
        
        self.keywords = @"汉堡包"; //初始设定一个默认词
    }
    return self;
}

- (void)getDataFromNet:(BOOL )isReqMore completeHandle:(void(^)(NSError *error))completionHandle {
    
    NSMutableDictionary *dicHeaders = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    NSMutableDictionary *dicParams = [[NSMutableDictionary alloc] initWithCapacity:0];
    ///
    if (self.keywords.length > 0) {
        [dicParams setValue:TX_STRING(self.keywords) forKey:@"q"];
    }
    ///
    if (!isReqMore) {
        self.pagenum = 0;
    } else {
        self.pagenum++;
    }
    [dicParams setValue:@(self.pagenum*self.pagesize) forKey:@"sn"];
    [dicParams setValue:@(self.pagesize) forKey:@"pn"];
    
    [[TXHttpService shareInstance] requestWithUrl:kUrlImageList headers:dicHeaders params:dicParams method:HttpGet cacheBlock:nil finishBlock:^(NSDictionary *jsonObj, NSError *error) {
        
        if (!error) {
            
            NSDictionary *list = [jsonObj objectForKey:@"list"];
            NSString *total = TX_STRING([jsonObj objectForKey:@"total"]);
            
            if (jsonObj && [jsonObj isKindOfClass:[NSDictionary class]] && jsonObj.count > 0) {

                NSMutableArray *arrObjs = [ImageListModel mj_objectArrayWithKeyValuesArray:list];
                
                if (!isReqMore) {
                    [self.dataArr removeAllObjects];
                }
                [self.dataArr addObjectsFromArray:arrObjs];
            }
            
            self.hasNext = ([total integerValue] > [self.dataArr count]);
        }
        
        completionHandle(nil);
    }];
}

- (NSInteger)rowNumber {
    return self.dataArr.count;
}

- (ImageListModel *)modelForRow:(NSInteger )row {
    return self.dataArr[row];
}

#pragma mark - Getter

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}

@end
